package ca.venasse.pinventory.inventory.common;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;

@Embeddable
public class PurchaseDate implements Serializable {

	private static final long serialVersionUID = 1L;

	public static PurchaseDate create(DateTime value) {
		checkNotNull(value, "error.cannot_be_blank");
		return new PurchaseDate(value);
	}

	@Column(name = "purchase_date", updatable = true, insertable = true)
	@org.hibernate.annotations.Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
	private DateTime value;

	protected PurchaseDate() {
	}

	private PurchaseDate(DateTime value) {
		this.value = value
			.withHourOfDay(12)
			.withMinuteOfHour(0)
			.withSecondOfMinute(0)
			.withMillisOfSecond(0);
	}

	public DateTime asDateTime() {
		return this.value;
	}

	public String asString() {
		return this.value == null ? null : ISODateTimeFormat.date().print(this.value);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof PurchaseDate)) {
			return false;
		}
		PurchaseDate other = (PurchaseDate) obj;
		if (this.value == null) {
			if (other.value != null) {
				return false;
			}
		} else if (!this.value.equals(other.value)) {
			return false;
		}
		return true;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (this.value == null ? 0 : this.value.hashCode());
		return result;
	}

	@Override
	public String toString() {
		return this.value.toString();
	}

}